package com.uniledger.exchange.welcome;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.uniledger.exchange.GuideActivity;
import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.login.Admin;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.wallet.CreateWalletActivity;
import com.uniledger.exchange.wallet.MnemonicActivity;

import org.stellar.sdk.KeyPair;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class WelcomeActivity extends BaseActivity {

    public static final String ROUTE_FLAG_TAG = "routeFlag";

    public static final short ROUTE_HOME_FLAG = 0;//跳转主页
    public static final short ROUTE_FEED_FLAG = 1;//跳转Feed流
    public static final short ROUTE_WEB_FLAG = 2;//跳转WEB
    public static final short ROUTE_PUSH_FLAG = 3;//推送跳转
    public static final short ROUTE_BACK_FLAG = 4;//后台切入热启动

    @BindView(R.id.img_splash)
    ImageView mSpBgImage;

    @BindView(R.id.sp_jump_btn)
    Button mSpJumpBtn;

    private int flag;
    @BindString(R.string.splash_skip)
    String skip;

    //由于CountDownTimer有一定的延迟，所以这里设置3400
    private CountDownTimer countDownTimer = new CountDownTimer(3400, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mSpJumpBtn.setText(String.format(skip, millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            mSpJumpBtn.setText(String.format(skip, 0));
            route(flag);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        getParams();
        showAndDownSplash();

        toolbar.setVisibility(View.GONE);
    }

    private void showAndDownSplash() {
        showSplash();
    }

    public void getParams() {
        Intent intent = getIntent();
        flag = intent.getShortExtra(ROUTE_FLAG_TAG, ROUTE_HOME_FLAG);
    }

    @Override
    public void initBar() {
        super.initBar();
    }

    @OnClick({R.id.img_splash, R.id.sp_jump_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_splash:
                gotoWebActivity();
                break;
            case R.id.sp_jump_btn:
                route(flag);
                break;
        }
    }

    private void gotoLoginOrMainActivity() {
        UniApp.getDb().adminDao().loadAdmin()
                .map(new Function<Admin, Admin>() {
                    @Override
                    public Admin apply(Admin admin) throws Exception {
                        OkSingleton.getInstance().setToken(admin.token);
                        OkSingleton.getInstance().setIssuingKeyPair(KeyPair.fromAccountId(admin.issuingAccountId));
                        OkSingleton.getInstance().setBaseKeyPair(KeyPair.fromAccountId(admin.baseAccountId));
                        return admin;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Admin>() {
                    @Override
                    public void accept(Admin admin) throws Exception {
                        if (admin.isSignIn) {
                            switch (admin.walletFlag) {
                                case 1://去创建钱包
                                    gotoCreateWalletActivity();
                                    break;
                                case 2://去备份钱包
//                                    gotoBackupWalletActivity();
                                    gotoMainActivity();
                                    break;
                                case 3://去主页
                                    gotoMainActivity();
                                    break;
                                default:
                                    gotoMainActivity();
                                    break;
                            }
                        } else {
                            gotoLoginActivity();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        gotoLoginActivity();
                    }
                });
    }

    /**
     * 去主页
     */
    private void gotoMainActivity() {
        HomeActivity.start(this);
//        EthActivity.start(this);
        finish();
    }

    /**
     * 去创建钱包
     */
    private void gotoCreateWalletActivity() {
        CreateWalletActivity.start(this);
        finish();
    }

    /**
     * 去创建钱包
     */
    private void gotoBackupWalletActivity() {
        MnemonicActivity.start(this);
        finish();
    }

    /**
     * 登录
     */
    private void gotoLoginActivity() {
        GuideActivity.start(this);
        finish();
    }


    private void gotoWebActivity() {

    }

    /**
     * 根据传入参数跳转不同的业务逻辑
     */
    private void route(int flag) {
        switch (flag) {
            case ROUTE_FEED_FLAG:
                break;
            case ROUTE_WEB_FLAG:
                break;
            case ROUTE_BACK_FLAG:
                finish();
                break;
            case ROUTE_PUSH_FLAG:
                break;
            default://登录或进入主页
                gotoLoginOrMainActivity();
                break;
        }

    }

    private void showSplash() {
        startClock();
    }

    private void startClock() {
        mSpJumpBtn.setVisibility(View.VISIBLE);
        countDownTimer.start();
    }

    @Override
    public void finish() {
        super.finish();
        //overridePendingTransition(0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null)
            countDownTimer.cancel();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
        //TODO 禁用返回键
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}
